package com.boot.app.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.app.file.domain.FileAttach;
import com.boot.app.file.domain.FileAttachGroup;
import com.boot.app.file.mapper.FileAttachGroupMapper;
import com.boot.app.file.service.IFileAttachService;
import com.boot.app.file.service.IFileAttachGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

@Service
public class FileAttachGroupServiceImpl extends ServiceImpl<FileAttachGroupMapper, FileAttachGroup> implements IFileAttachGroupService {

    private static String FILE_PATH = "static/";

    private final FileAttachGroupMapper fileAttachGroupMapper;

    private final IFileAttachService attachService;

    @Autowired
    public FileAttachGroupServiceImpl(
        FileAttachGroupMapper fileAttachGroupMapper,
        IFileAttachService attachService
    ){
        this.fileAttachGroupMapper = fileAttachGroupMapper;
        this.attachService = attachService;
    }

    @Transactional
    @Override
    public boolean removeById(long id) throws FileNotFoundException {
        LambdaQueryWrapper<FileAttach> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileAttach::getGroupId, id);
        List<FileAttach> fileAttachList = attachService.list(queryWrapper);

        attachService.remove(queryWrapper);

        fileAttachGroupMapper.deleteById(id);

        String classPath = ResourceUtils.getURL("classpath:").getPath();
        fileAttachList.forEach(ele -> {
            File file = new File(classPath + FILE_PATH + ele.getName());
            if(file.exists()) {
                file.delete();
            }
        });
        return true;
    }

}
